package com.demo.common.controller;

import java.util.Date;
import java.util.List;

import com.demo.common.model.Blog;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.NoUrlPara;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.upload.UploadFile;

public class BlogController extends Controller {
	@Before(NoUrlPara.class)
	public void index(){
		System.out.println("执行index");
		setAttr("blogs", Blog.dao.find("select * from blog"));
		render("index.jsp");
	}
	public void form(){
		Integer id=getParaToInt("id");
		if(id!=null&&id>0){
			setAttr("blog", Blog.dao.findById(id));
		}
		render("form.jsp");
	}
	
	public void save(){
		long count=0;
		List result=Db.query("select count(*) from blog");
		if(result.size()==1){
			count = ((Number)result.get(0)).longValue();	
		}else if(result.size()>1){
			count=result.size();
		}
		if((int)count>=10){
			render("count.html");
			return;
		}
		UploadFile file=getFile("img");
		Blog blog=getModel(Blog.class, "blog");
		if(blog.get("id")==null){
			blog.set("publishTime", new Date());
			blog.save();
		}else if(blog.getInt("id")>0){
			blog.update();
		}
		
		redirect("/blog");
	}
	
	public void delete(){
		Integer id=getParaToInt("id");
		if(id!=null&&id>0){
			boolean flag=Blog.dao.deleteById(id);
			if(!flag){
				renderText("删除失败!");
				return;
			}
		}else{
			renderText("删除失败!");
			return;
		}
		redirect("/blog");
	}
	

}
